// 导入用户集合
const { Article } = require('../../../model/article');
const { Comment } = require('../../../model/comment');
// 引入分页模块
const pagination = require('mongoose-sex-page')

module.exports = async (req, res) => {
  const { pageIndex, pageSize, category } = req.query
  let query = {
      state: 1
  }
  if (category) {
      query.category = category
  }
  console.log(query)
  let articles = await pagination(Article).find(query).sort({_id: -1}).page(pageIndex).size(pageSize).populate('category author').exec()
  let list = []
  articles.records.forEach(async (item, index) => {
	  const comments = await Comment.find({article: item._id})
	  list.push({
		  ...item.toObject(),
		  comments: comments.length
	  })
	  if (index === articles.records.length - 1) {
		  res.json({
		      data: {
				  ...articles,
				  records: [...list]
			  }
		  })
	  }
  })
  
}